package com.mammoth.Bodybuilding.controller.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mammoth.Bodybuilding.entity.ResultObj;
import com.mammoth.Bodybuilding.entity.SysMenu;
import com.mammoth.Bodybuilding.entity.SysUserObj;
import com.mammoth.Bodybuilding.service.IMenuService;
import com.mammoth.Bodybuilding.service.IRoleService;
import com.mammoth.Bodybuilding.service.IUserService;
import com.mammoth.Bodybuilding.util.ClientType;
import com.mammoth.Bodybuilding.util.CurrencySaas;
import com.mammoth.Bodybuilding.util.RoleType;

import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;

/**
 * 
 * @title : UserController
 * @description : 后台 用户 控制器
 * @company : com.mammoth.Bodybuilding.controller.web
 * @project Mammoth
 * @author xingzhaojun
 * @date 2018年4月13日 上午11:01:00
 */
@Controller
public class UserController {

	/** 注入用户service **/
	@Autowired
	private IUserService userService;

	/** 注入用户service **/
	@Autowired
	private IRoleService roleService;

	/** 注入菜单数据仓库 **/
	@Autowired
	private IMenuService menuService;

	/** 注入图片验证码 **/
	@Autowired
	private DefaultKaptcha defaultKaptcha;

	/** 项目名称 **/
	@Value(value = "${project.name}")
	private String projectName;

	/**
	 * pc端首页位置
	 * 
	 * @return 首页映射
	 */
	@GetMapping(value = "/login")
	public String indexPage(Model model, HttpServletRequest request) {
		model.addAttribute("user", new SysUserObj());
		model.addAttribute("resultObj", null);
		return "login";
	}

	/**
	 * 后台登录后跳转首页
	 * 
	 * @param request
	 *            request对象
	 * @return
	 */
	@GetMapping(value = "/")
	public String homePage(HttpServletRequest request) {
		/** 获取用户信息 **/
		SysUserObj user = (SysUserObj) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		HttpSession session = request.getSession();
		/** 主菜单 **/
		List<SysMenu> menu = menuService.getMenuByFidAndRole(0, user.getSysRoles());
		List<SysMenu> menuSon = new ArrayList<>();
		for (SysMenu sysMenu : menu) {
			menuSon.addAll(menuService.getMenuByFidAndRole(sysMenu.getId(), user.getSysRoles()));
		}

		session.removeAttribute("user");
		session.removeAttribute("menu");
		session.removeAttribute("menuSon");

		session.setAttribute("user", user);
		session.setAttribute("menu", menu);
		session.setAttribute("menuSon", menuSon);
		/** 保存项目名称 **/
		request.getServletContext().setAttribute("projectName", projectName);

		return "home";
	}

	/**
	 * 注册接口
	 * 
	 * @param user
	 *            用户信息
	 * @param result
	 *            获取校验用户信息错误
	 * @param checkPass
	 *            密码确认
	 * @param model
	 *            request对象
	 * @return
	 */
	@PostMapping(value = "/register")
	public String register(@ModelAttribute @Valid SysUserObj user, BindingResult result, @RequestParam String checkPass,
			Model model) {
		/** 调用service **/
		ResultObj resultObj = userService.registUser(user, checkPass, ClientType.PCMANAGETYPE, result);
		model.addAttribute("user", new SysUserObj());
		model.addAttribute("resultObj", resultObj);
		/** 注册成功,跳转成功页面 **/
		return "login";
	};

	/**
	 * 忘记密码接口
	 * 
	 * @param userNameForget
	 *            登录名
	 * @param model
	 *            model对象
	 * @param request
	 *            request对象
	 * @return
	 */
	@PostMapping(value = "/forget")
	public String forget(@RequestParam String userNameForget, Model model, HttpServletRequest request) {
		ResultObj resultObj = userService.forgetPassword(userNameForget, request);
		model.addAttribute("user", new SysUserObj());
		model.addAttribute("resultObj", resultObj);
		return "login";
	}

	/**
	 * 忘记密码页面
	 * 
	 * @param uuid
	 *            uuid
	 * @param model
	 *            model对象
	 * @return
	 */
	@GetMapping(value = "/forget/{uuid}")
	public String forgetPage(@PathVariable String uuid, Model model) {
		model.addAttribute("uuid", uuid);
		return "forgetpage";
	}

	/***
	 * 重置密码
	 * 
	 * @param uuid
	 *            标识id
	 * @param password
	 *            密码
	 * @param checkPassword
	 *            检查密码
	 * @param request
	 *            request 对象
	 * @param model
	 *            model 对象
	 * @return
	 */
	@PostMapping(value = "/reset")
	public String resetPass(@RequestParam String uuid, @RequestParam @Valid String loginPassword,
			@RequestParam @Valid String checkPassword, HttpServletRequest request, Model model) {
		ResultObj resultObj = userService.resetPassword(uuid, loginPassword, checkPassword);
		model.addAttribute("user", new SysUserObj());
		model.addAttribute("resultObj", resultObj);
		return "login";
	}

	/**
	 * 修改用户信息
	 * 
	 * @param LoginName
	 *            登录名
	 * @param nickName
	 *            昵称
	 * @param tel
	 *            电话
	 * @param email
	 *            电子邮件
	 * @param role
	 *            角色
	 * @param model
	 *            model权限
	 * @return
	 */
	@PostMapping(value = "/updateUser")
	@ResponseBody
	public String updateUser(@RequestParam String loginName, @RequestParam String nickName, @RequestParam String tel,
			@RequestParam String email, @RequestParam String role, Model model) {
		/** 获取用户信息 **/
		SysUserObj user = (SysUserObj) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<RoleType> roles = new ArrayList<>();
		roles.add(RoleType.ROLE_PROGRAM);
		roles.add(RoleType.ROLE_ADMIN);
		JSONObject flag = CurrencySaas.checkUserRole(user, roles);
		if (flag.getBoolean("flag")) {
			ResultObj result = userService.updateUser(loginName, nickName, tel, email, role);
			model.addAttribute("result", result);
			return JSONObject.fromObject(result).toString();
		} else {
			JSONObject json = new JSONObject();
			json.put("flag", false);
			json.put("message", "当前用户没有权限");
			return json.toString();
		}
	}

	/**
	 * 查询用户信息列表
	 * 
	 * @param model
	 *            model对象
	 * @return
	 */
	@GetMapping(value = "/alluser")
	public String allUser(Model model) {
		/** 获取用户信息 **/
		SysUserObj user = (SysUserObj) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<RoleType> roles = new ArrayList<>();
		roles.add(RoleType.ROLE_PROGRAM);
		roles.add(RoleType.ROLE_ADMIN);
		JSONObject flag = CurrencySaas.checkUserRole(user, roles);
		if (flag.getBoolean("flag")) {
			/** 菜单开启状态 **/
			SysMenu menu = menuService.getMenuByPath("/alluser");
			model.addAttribute("pageid", menu.getFid());
			model.addAttribute("page", menu.getMenuPath());
			return "manageruser";
		} else {
			return "error";
		}
	}

	/**
	 * 
	 * @param pageSize
	 *            分页数
	 * @param pageIndex
	 *            当前页数
	 * @param Name
	 *            登录名
	 * @param Tel
	 *            电话
	 * @return
	 * @throws JSONException
	 */
	@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
	@PostMapping(value = "/getalluser")
	@ResponseBody
	public String getAllUser(@RequestParam int pageSize, @RequestParam int pageIndex, @RequestParam String name,
			@RequestParam String tel) {
		JSONObject json = new JSONObject();
		/** 获取用户信息 **/
		SysUserObj user = (SysUserObj) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		List<RoleType> roles = new ArrayList<>();
		roles.add(RoleType.ROLE_PROGRAM);
		roles.add(RoleType.ROLE_ADMIN);
		JSONObject flag = CurrencySaas.checkUserRole(user, roles);
		if (flag.getBoolean("flag")) {
			ResultObj users = userService.getAllUser(pageSize, pageIndex, name, tel);
			json.put("res", users.getResult());
			json.put("total", users.getTotal());
			json.put("flag", users.isFlag());
			json.put("msg", users.getMessage());
		} else {
			json.put("flag", false);
			json.put("msg", "当前用户没有权限");
		}
		return json.toString();
	}

	/**
	 * 获取角色列表
	 * 
	 * @return
	 * @throws JSONException
	 */
	@ApiOperation(value = "角色列表", notes = "获取角色列表")
	@GetMapping(value = "/getrole")
	@ResponseBody
	public String getRole() {
		ResultObj role = roleService.getAllRole();
		JSONObject json = new JSONObject();
		json.put("res", role.getResult());
		json.put("total", role.getTotal());
		json.put("flag", role.isFlag());
		json.put("msg", role.getMessage());
		return json.toString();
	}

	/**
	 * 根据用户id删除用户
	 * 
	 * @param userId
	 *            用户id
	 * @return
	 * @throws JSONException
	 */
	@ApiOperation(value = "根据id删除用户信息")
	@PostMapping(value = "/deleuser")
	@ResponseBody
	public String deleteUser(@RequestParam(value = "ids[]") Long[] ids) {
		/** 获取用户信息 **/
		SysUserObj user = (SysUserObj) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		/** 判断是否有权限访问该接口 **/
		if (!user.getSysRoles().getName().equals(RoleType.ROLE_PROGRAM.toString())) {
			return "error";
		}

		ResultObj resultObj = userService.deleteUsers(ids);
		JSONObject json = new JSONObject();
		json.put("res", resultObj.getResult());
		json.put("total", resultObj.getTotal());
		json.put("flag", resultObj.isFlag());
		json.put("msg", resultObj.getMessage());
		return json.toString();
	}

	/**
	 * 图片验证码
	 * 
	 * @param httpServletRequest
	 * @param httpServletResponse
	 * @throws Exception
	 */
	@GetMapping("/defaultKaptcha")
	public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
			throws Exception {
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			// 生产验证码字符串并保存到session中
			String createText = defaultKaptcha.createText();
			httpServletRequest.getSession().setAttribute("vrifyCode", createText);
			// 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = defaultKaptcha.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		// 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");
		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}

}
